<?php
function ShowMsg(String $msg, $url = null)
{
    // 定义一个空字符串
    $str = '';
    if ($url) {
        $str = "
                <script>
                    alert('$msg');
                    location.href = '$url';
                </script>
            ";
    } else {
        $str = "
                <script>
                    alert('$msg');
                    history.go(-1);
                </script>
            ";
    }

    // 调用函数直接输出
    echo $str;
}
include_once('config.php');
if ($_POST) {
    $jobname = $_POST['name'];
    $depid = $_POST['depid'];
    $id = $_POST['jobid'];
    $sql = "UPDATE `pre_job` set `name` = '$jobname',`depid` = '$depid' WHERE `id` = '$id'";
    $res = mysqli_query($conn, $sql);
    if ($res) {
        ShowMsg('更新成功', 'index.php');
        exit;
    } else {
        ShowMsg('更新失败');
        exit;
    }
}

// 在php写sql语句
$depsql = "SELECT * FROM `pre_department`";

// 执行sql语句
$res = mysqli_query($conn, $depsql);

// 存放返回的数据
$DepData = [];

// 返回结果== true && 返回的行大于0
if ($res && mysqli_num_rows($res) > 0) {
    while ($data = mysqli_fetch_assoc($res)) {
        $DepData[] = $data;
    }
}


$id = $_GET['id'];

$sql = "SELECT * FROM `pre_job` WHERE `id` = '$id'";

// 执行sql语句
$res = mysqli_query($conn, $sql);

// 存放返回的数据
$job = [];

// 返回结果== true && 返回的行大于0
if ($res && mysqli_num_rows($res) > 0) {
    $job = mysqli_fetch_assoc($res);
}
if (!$job) {
    ShowMsg('该条数据无法编辑，请重新选择', 'index.php');
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <h1>编辑</h1>
    <form method="post">
        <input type="hidden" name="jobid" value="<?php echo $job['id']; ?>">
        <table>
            <tr>
                <td>职位名称</td>
                <td>
                    <input type="text" name="name" value="<?php echo $job['name']; ?>">
                </td>
            <tr>
                <td>部门名称</td>
                <td>
                    <select name="depid">
                        <?php foreach ($DepData as $item) { ?>
                            <option value="<?php echo $item['id']; ?>" <?php echo $item['id'] == $job['depid'] ? 'selected' : '' ?>><?php echo $item['name']; ?></option>
                        <?php } ?>
                    </select>
                </td>
            </tr>
            <tr>
                <td></td>
                <td>
                    <button type="submit">提交</button>
                </td>
            </tr>
            </tr>
        </table>
    </form>
</body>
</html>